package com.pda.common.pages.relationscanf;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import com.pda.common.R;
import com.pda.common.basemvp.activity.BaseActivity;
import com.pda.common.bean.CaseBoxBean;
import com.pda.common.bean.BillBean;
import com.pda.common.beanin.ScanfInBean;
import com.pda.common.broadcast.NetWorkChangReceiver;
import com.pda.common.database.CodeInfo;
import com.pda.common.database.DataBaseControl;
import com.pda.common.database.ProductInfo;
import com.pda.common.dialogs.ChooseDialog;
import com.pda.common.scan.BroadcastConfig;
import com.pda.common.tools.SharedPreferencesManger;
import com.pda.common.tools.StringProcess;
import com.pda.common.tools.VoiceUtils;
import com.pda.common.utils.PDAUtil;
import com.zhy.view.flowlayout.TagFlowLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RelationScanfCActivity extends BaseActivity<RelationScanfModel, RelationScanfView, RelationScanfPresent> implements RelationScanfView {
    private String TAG = "RelationScanfCActivity";
    @BindView(R.id.tvcasenumslocal)
    TextView tvcasenumslocal;
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tvright)
    TextView tvright;
    @BindView(R.id.tvbill)
    TextView tvbill;
    @BindView(R.id.tvpid)
    TextView tvpid;
    @BindView(R.id.tvname)
    TextView tvname;
    @BindView(R.id.tvbatch)
    TextView tvbatch;
    @BindView(R.id.tvcasenums)
    TextView tvcasenums;
    @BindView(R.id.curbox)
    TextView curbox;
    @BindView(R.id.totalbox)
    TextView totalbox;
    @BindView(R.id.tvcasenumss)
    TextView tvcasenumss;
    @BindView(R.id.id_flowlayout)
    TagFlowLayout idFlowlayout;
    @BindView(R.id.tvword)
    TextView tvword;
    @BindView(R.id.sws)
    Switch sws;
    @BindView(R.id.qzzx)
    Button qzzx;
    @BindView(R.id.tvs)
    TextView tvs;
    NetWorkChangReceiver netWorkChangReceiver;
    boolean flag = true;
    BillBean billBean = null;
    ScanfInBean scanfInBean = new ScanfInBean();
    CaseBoxBean caseBoxBean = new CaseBoxBean();//当前扫描箱盒数据
    int caseBoxNums = 0; //每箱的产品规格数量
    int ynum = 0; //应扫数量
    int snum = 0; //实扫数量
    VoiceUtils voiceUtils;

    protected BroadcastReceiver mScanfBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BroadcastConfig.CUSTOM_NAME)) {
                String code = StringProcess.codeCL(intent.getStringExtra("scannerdata"));
                CodeInfo codeInfo = new CodeInfo();
                codeInfo.setBill(billBean.getData().get(0).getBillID());
                codeInfo.setCode(code);
                codeInfo.setType(PDAUtil.RELATION);
                if (flag) {
                    if (ynum <= snum) {
                        showres("实扫数量已达到应扫数量");
                        voiceUtils.voiceWarn(mContext);
                        return;
                    }
                    if (caseBoxBean.getBoxcodes().size() == caseBoxNums)//扫箱
                    {
                         if (StringProcess.casecodeJudge(code)) {
                             if (DataBaseControl.addCode(codeInfo) == -1) {
                                 showres("箱码重复");
                                 voiceUtils.voiceWarn(mContext);
                                 return;
                             }

                             caseBoxBean.setCasecode(code);
                             BillBean billBean1 = presenter.addcode(scanfInBean, caseBoxBean);
                             if(billBean1.getErrcode()==0)
                             {
                                 uiupdate(billBean1);
                                 showres("新增箱码:" + code);
                             }
                             else
                             {
                                 voiceUtils.voiceWarn(mContext);
                                 showres(billBean1.getErrmsg());
                                 //失败就删除之前的本地条码
                                 DataBaseControl.deleteCode(codeInfo);
                                 for (int i = 0; i <caseBoxBean.getBoxcodes().size() ; i++) {
                                     CodeInfo codeInfot = new CodeInfo();
                                     codeInfot.setBill(billBean.getData().get(0).getBillID());
                                     codeInfot.setCode(caseBoxBean.getBoxcodes().get(i));
                                     codeInfot.setType(PDAUtil.RELATION);
                                     DataBaseControl.deleteCode(codeInfot);
                                 }
                             }
                             caseBoxBean.setCasecode("");
                             caseBoxBean.getBoxcodes().clear();
                             curbox.setText(caseBoxBean.getBoxcodes().size() + "");
                        } else {
                            showres("请扫箱码");
                             voiceUtils.voiceWarn(mContext);;
                        }
                    }
                    else //扫盒
                    {
                        if (StringProcess.boxcodeJudge(code)) {
                            if (caseBoxBean.getBoxcodes().contains(code)) {
                                showres("盒码重复");
                                voiceUtils.voiceWarn(mContext);
                            } else if (DataBaseControl.addCode(codeInfo) == -1) {
                                showres("盒码重复");
                                voiceUtils.voiceWarn(mContext);
                            } else {
                                caseBoxBean.getBoxcodes().add(code);
                                showres("新增盒码:" + code);
                                curbox.setText(caseBoxBean.getBoxcodes().size() + "");
                            }
                        } else {
                            showres("请扫盒码");
                            voiceUtils.voiceWarn(mContext);
                        }
                    }
                }
                else {
                    if (StringProcess.boxcodeJudge(code)) {
                        caseBoxBean.getBoxcodes().remove("");
                        if (caseBoxBean.getBoxcodes().contains(code)) {
                            caseBoxBean.getBoxcodes().remove(code);
                            DataBaseControl.deleteCode(codeInfo);
                            showres("删除盒码:" + code);
                            curbox.setText(caseBoxBean.getBoxcodes().size() + "");
                        } else {
                            showres("当前箱无此盒码");
                            voiceUtils.voiceWarn(mContext);
                            return;
                        }
                    } else {
                        showres("盒码长度不符");
                        voiceUtils.voiceWarn(mContext);
                        return;
                    }
                }
            }
        }
    };

    @Override
    protected void initdata() {
        tvTitle.setText("生产扫描");
        tvright.setVisibility(View.VISIBLE);
        tvright.setBackgroundResource(R.drawable.rect_blue);
        tvright.setText(" 完成 ");
        sws.setChecked(true);
        sws.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    flag = isChecked;
                } else {
                    flag = isChecked;
                }
            }
        });
        billBean = (BillBean) getIntent().getSerializableExtra(PDAUtil.keyBillDeatial);

        tvbill.setText("单号:" + billBean.getData().get(0).getBillCode());
        tvpid.setText("产品编码:" + billBean.getData().get(0).getProductID());
        tvname.setText("产品名称:" + billBean.getData().get(0).getProductName());
        tvbatch.setText("批次:" + billBean.getData().get(0).getBatch());

        ynum = billBean.getData().get(0).getyScanNums();
        snum = billBean.getData().get(0).getsScanNums();
        tvcasenums.setText("" + ynum);
        tvcasenumss.setText("" + snum);
        tvcasenumslocal.setText("" + 0);

        try {
            ProductInfo productInfo = DataBaseControl.getProductID(billBean.getData().get(0).getProductID()).get(0);
            caseBoxNums = productInfo.getCaseBoxNums();
            totalbox.setText(caseBoxNums + "");
        }
        catch (Exception e)
        {
            showMsg("当前产品信息未同步 请重新下载基础信息");
            finish();
        }

        scanfInBean.setAction("UpdateCodes");
        scanfInBean.setCid(SharedPreferencesManger.getCid());
        scanfInBean.setUserID(SharedPreferencesManger.getUID());
        scanfInBean.setStoreID(SharedPreferencesManger.getStoreID());
        scanfInBean.setBillID(billBean.getData().get(0).getBillID());
        scanfInBean.setBillListID(billBean.getData().get(0).getBillListID());
        scanfInBean.setProductID(billBean.getData().get(0).getProductID());
        scanfInBean.setIsVirtualTuo(0);
        scanfInBean.setBillType(PDAUtil.RELATION);
        scanfInBean.setBillCode(billBean.getData().get(0).getBillCode());

        netWorkChangReceiver = new NetWorkChangReceiver(new NetWorkChangReceiver.PriorityListener() {
            @Override
            public void setText(String string) {
                tvs.setText(string);
            }
        });
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkChangReceiver, filter);

        initBroadcastReciever();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastConfig.CUSTOM_NAME);
        registerReceiver(mScanfBroadcastReceiver, intentFilter);
        voiceUtils= new VoiceUtils();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_relation_scanf);
        ButterKnife.bind(this);
        initdata();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkChangReceiver);
        unregisterReceiver(mScanfBroadcastReceiver);
    }

    @Override
    public RelationScanfModel createModel() {
        return new RelationScanfModelImpl(this);
    }

    @Override
    public RelationScanfView createView() {
        return this;
    }

    @Override
    public RelationScanfPresent createPresenter() {
        return new RelationScanfPresent();
    }

    @Override
    public void uiupdate(final BillBean BillBean) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                snum = BillBean.getData().get(0).getSScanNums();
                tvcasenumss.setText(snum + "");
            }
        });

//        String[] mVals = new String[mAbBillBean.getBoxNum()];
//        Collections.reverse(mAbBillBean.getBoxcodes());
//        for (int i = 0; i < mAbBillBean.getBoxcodes().size(); i++) {
//            mVals[i] = mAbBillBean.getBoxcodes().get(i);
//        }
//        int k = 0;
//        for (int i = mAbBillBean.getBoxcodes().size(); i > 0; i--) {
//            mVals[k] = mAbBillBean.getBoxcodes().get(i - 1);
//            k++;
//        }
//        idFlowlayout.setAdapter(new TagAdapter<String>(mVals) {
//            @Override
//            public View getView(FlowLayout parent, int position, String s) {
//                TextView tv = (TextView) LayoutInflater.from(mContext).inflate(R.layout.tv, idFlowlayout, false);
//                tv.setText(s);
//                return tv;
//            }
//        });
    }

    @Override
    public void showres(final String str) {
        if(str==null)
        {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvword.setText(str);
            }
        });
        if (str.equals(PDAUtil.billFinish)) {
            finish();
        }
    }

    @OnClick({R.id.iv_title_left, R.id.tvright, R.id.qzzx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                ChooseDialog nDialog = new ChooseDialog(this, PDAUtil.exitScanf, R.style.Dialog1, new ChooseDialog.PriorityListener() {
                    @Override
                    public void setActivityText() {
                        finish();
                    }
                });
                WindowManager.LayoutParams lp = nDialog.getWindow().getAttributes();
                lp.gravity = Gravity.CENTER;
                nDialog.setCanceledOnTouchOutside(false);
                nDialog.show();
                break;
            case R.id.qzzx:
                if (caseBoxBean.getBoxcodes().size() != 0 && caseBoxBean.getBoxcodes().size() != caseBoxNums) {
                    int j = caseBoxBean.getBoxcodes().size() ;
                    for (int i = j; i < caseBoxNums; i++) {
                        caseBoxBean.getBoxcodes().add("");
                    }
                    curbox.setText(j + "");
                    showres("强制装箱");
                } else {
                    showres("当前扫描盒码数不满足强制装箱");
                }
                break;
            case R.id.tvright:
                ScanfInBean scanfInBean = new ScanfInBean();
                scanfInBean.setAction("CommitBill");
                scanfInBean.setCid(SharedPreferencesManger.getCid());
                scanfInBean.setUserID(SharedPreferencesManger.getUID());
                scanfInBean.setStoreID(SharedPreferencesManger.getStoreID());
                scanfInBean.setBillID(billBean.getData().get(0).getBillID());
                scanfInBean.setBillType(PDAUtil.RELATION);
                scanfInBean.setBillCode(billBean.getData().get(0).getBillCode());
                presenter.fb(scanfInBean);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            ChooseDialog nDialog = new ChooseDialog(this, PDAUtil.exitScanf, R.style.Dialog1, new ChooseDialog.PriorityListener() {
                @Override
                public void setActivityText() {
                    finish();
                }
            });
            WindowManager.LayoutParams lp = nDialog.getWindow().getAttributes();
            lp.gravity = Gravity.CENTER;
            nDialog.setCanceledOnTouchOutside(false);
            nDialog.show();
        }
        return super.onKeyDown(keyCode, event);
    }
}
